package com.hpe.aruba.CPPM;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.PreferenceManager;

import com.hpe.aruba.CPPM.enums.SharedPrefFields;
import com.hpe.aruba.CPPM.objects.Device;

import java.util.ArrayList;
import java.util.Date;


public class SortEndpointsActivity extends AppCompatActivity {

    Intent intent;

    private static final String DEVICES = "com.hpe.aruba.CPPM.DEVICES";

    SharedPreferences sharedPreferences;

    private ArrayList<Device> macs;
    private ArrayList<Device> staticMacs;

    private ArrayList<Device> filterRest;
    private boolean order;

    static int sortRadioNumber;
    static int statusRadioNumber;
    static boolean statusBoxChecked;

    private SeekBar timeFilterBar;

    private TextView timeFilterText;

    private CheckBox checkBoxStatus;

    private RadioGroup sortRadioGroup;
    private RadioButton radio_mac;
    private RadioButton radio_date;

    private RadioGroup statusRadioGroup;
    private RadioButton knownStatusRadio;
    private RadioButton unknownStatusRadio;
    private RadioButton disabledStatusRadio;


    private Button button1;
    private Button button2;

    private String[] getUntils;


    @Override
    public void onCreate (@Nullable Bundle savedInstanceState/*ManageMacsActivity context, ArrayList<Device> macs*/) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sort_activity_endpoints);

        intent = getIntent();
        macs = intent.getParcelableArrayListExtra(DEVICES);
        filterRest = intent.getParcelableArrayListExtra("VENDORFILTERREST");
        staticMacs = intent.getParcelableArrayListExtra("STATIC_MACS");
        sortRadioNumber = intent.getIntExtra("LAST_SORT", -1);
        order = intent.getBooleanExtra("ORDER",false);

        sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(this /* Activity context */);
        order = sharedPreferences.getBoolean(SharedPrefFields.ENDPOINT_SORT.ORDER.toString(), false);
        statusBoxChecked = sharedPreferences.getBoolean(SharedPrefFields.ENDPOINT_SORT.STATUS_FILTER_CHECKED.toString(), false);
        statusRadioNumber = sharedPreferences.getInt(SharedPrefFields.ENDPOINT_SORT.STATUS_RADIO_NUMBER.toString(), 0);
        sortRadioNumber = sharedPreferences.getInt(SharedPrefFields.ENDPOINT_SORT.SORT_RADIO_NUMBER.toString(), 0);

        initFields(macs);

        getUntils = getResources().getStringArray(R.array.getUntils);


               byte progress = (byte) sharedPreferences.getInt("GET_UNTIL_SELECTION", 7);
        timeFilterText.setText(getString(R.string.get_devices_from,getUntils[progress]));
        timeFilterBar.setProgress(progress);

        timeFilterBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
             @Override
             public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                 timeFilterText.setText(getString(R.string.get_devices_from,getUntils[progress]));
             }

             @Override
             public void onStartTrackingTouch(SeekBar seekBar) {

             }

             @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void initFields(ArrayList<Device> macs) {
        button1 = findViewById(R.id.buttonSubmit);
        button2 = findViewById(R.id.buttonCancel);

        timeFilterBar = findViewById(R.id.seekBar);
        timeFilterText = findViewById(R.id.seekBarText);

        statusRadioGroup = findViewById(R.id.statusRadioGroup);
        setRadioGroupVisibility(statusRadioGroup, statusBoxChecked);
        knownStatusRadio = findViewById(R.id.radio_filter_known);
        unknownStatusRadio = findViewById(R.id.radio_filter_unknown);
        disabledStatusRadio = findViewById(R.id.radio_filter_disabled);

        checkBoxStatus = findViewById(R.id.checkBox_status);
        checkBoxStatus.setChecked(statusBoxChecked);

        sortRadioGroup = findViewById(R.id.sort_radioGroup);
        radio_mac = findViewById(R.id.radio_mac);
        radio_date = findViewById(R.id.radio_date);
        /*Sets the lastSort as the pre-selected Radio*/
        setPreSelectedSortRadio();
        if (statusBoxChecked) {
            setPreSelectedStatusRadio();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_confirm, menu);
        return true;
    }

    /**Only shows the Status-filter RadioGroup, if the Box for the status-filter is checked
     */
    private void setRadioGroupVisibility(RadioGroup radioGroup, boolean bool){
        radioGroup.setVisibility(bool ? View.VISIBLE : View.GONE);
    }

    /**Sets sort radioNumber depending on the radio button that was selected.
     * sortRadioNumber is set according to the cases in ManageMacsActivity -> sortList(n)
     */
    private void setSortRadioNumber(RadioGroup radioGroup){
        switch(radioGroup.getCheckedRadioButtonId()){
            case R.id.radio_mac:
                sortRadioNumber = 0;
                break;
            case R.id.radio_date:
                sortRadioNumber = 1;
                break;
            case R.id.radio_vendor:
                sortRadioNumber = 2;
                break;
        }
    }

    private void setPreSelectedSortRadio(){
        switch (sortRadioNumber){
            case 0:
                radio_mac.setChecked(true);
                break;
            case 1:
                radio_date.setChecked(true);
                break;
        }
    }

    private void setPreSelectedStatusRadio(){
        switch(statusRadioNumber){
            case 0:
                knownStatusRadio.setChecked(true);
                break;
            case 1:
                unknownStatusRadio.setChecked(true);
                break;
            case 2:
                disabledStatusRadio.setChecked(true);
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.confirm:
                handleSelections(macs);
                return true;
            default:
                setResult(RESULT_CANCELED);
                finish();
                return true;
        }
    }

    /**save all the checkBoxes and radioButtons states handle the functionality of the checked boxes*/
    private void handleSelections(ArrayList<Device> macs){
        if (checkBoxStatus.isChecked()){
            statusBoxChecked = true;
            filterByStatus(statusRadioGroup);
        } else {
            statusBoxChecked = false;
            statusRadioGroup.clearCheck();
        }
        byte progress = (byte) timeFilterBar.getProgress();

        //if(!checkBoxNetwork.isChecked() && !checkBoxStatus.isChecked() && !checkBoxVendor.isChecked()){ context.resetMacs();}
        /**TODO: Refresh Mac List based on sort here - Instead of resetting all just remember the items that are no longer in the list*/

        /*Gives back all the selections so the Mac List can be sorted in ManageMacsActivity*/
        setSortRadioNumber(sortRadioGroup);
        //context.sortList(sortRadioNumber);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putInt(SharedPrefFields.ENDPOINT_SORT.GET_UNTIL_SELECTION.toString(), progress);
        edit.putBoolean(SharedPrefFields.ENDPOINT_SORT.STATUS_FILTER_CHECKED.toString(), statusBoxChecked);
        edit.putInt(SharedPrefFields.ENDPOINT_SORT.STATUS_RADIO_NUMBER.toString(), statusRadioNumber);
        edit.putInt(SharedPrefFields.ENDPOINT_SORT.SORT_RADIO_NUMBER.toString(), sortRadioNumber);
        edit.putBoolean(SharedPrefFields.ENDPOINT_SORT.ORDER.toString(), order);
        edit.apply();

        Intent intent = new Intent();
        intent.putParcelableArrayListExtra("DEVICES", macs);
        setResult(RESULT_OK, intent);
        finish();
    }


    public void onEndpointsCheckboxClicked(View view){
        boolean checked;
        switch (view.getId()){
            case R.id.checkBox_status:
                checked = ((CheckBox) view).isChecked();
                if (checked){
                    statusBoxChecked = true;
                    setRadioGroupVisibility(statusRadioGroup,true);
                } else {
                    statusBoxChecked = false;
                    setRadioGroupVisibility(statusRadioGroup, false);
                }
                break;
            case R.id.checkBox_status_row:
                CheckBox statusBox = findViewById(R.id.checkBox_status);
                statusBox.toggle();
                onEndpointsCheckboxClicked(statusBox);
                break;

        }

    }

    private void filterByStatus(RadioGroup radioGroup){
        switch (radioGroup.getCheckedRadioButtonId()){
            case R.id.radio_filter_known:
                statusRadioNumber = 0;
                //TODO filter known
                break;
            case R.id.radio_filter_unknown:
                statusRadioNumber = 1;
                //TODO filter unknown
                break;
            case R.id.radio_filter_disabled:
                statusRadioNumber = 2;
                //TODO Filter diabled
                break;
        }
    }
    public void changeOrderEndpoints(View view){
        order = !order;
        ImageButton sort_arrow = (ImageButton) view;
        sort_arrow.setImageDrawable(getResources().getDrawable((order ? R.drawable.ic_arrow_down_24dp : R.drawable.ic_arrow_up_24dp), null));
    }

    public static Date getUnixTimeStampFromProgress(byte progress) {
        /*see timeFilters
         * future reader: this could probably be made more elegant. If API-increse: localdate class*/
        long time = System.currentTimeMillis();
        final long millisecondsInADay =  (24 * 60 * 60 * 1000);
        Date getUntil = new Date(time - time % millisecondsInADay);
        //long test = c.getTimeInMillis();

        switch (progress) {
            case 0: /*today*/
                break;
            case 1: /*one week*/
                getUntil.setTime(getUntil.getTime() - 7 * millisecondsInADay);
                break;
            case 2: /*two weeks*/
                getUntil.setTime(getUntil.getTime() - 14 * millisecondsInADay);
                break;
            case 3: /*one month*/
                getUntil.setTime(getUntil.getTime() - 30 * millisecondsInADay);
                break;
            case 4: /*three months*/
                getUntil.setTime(getUntil.getTime() - 90 * millisecondsInADay);
                break;
            case 5: /*six months*/
                getUntil.setTime(getUntil.getTime() - 180 * millisecondsInADay);
                break;
            case 6: /*12 months*/
                getUntil.setTime(getUntil.getTime() - 360 * millisecondsInADay);
                break;
            default:
                /*get all, including those without insight*/
                getUntil.setTime(0);
        }
        return getUntil;
    }
}


